package actions;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.*;


/**
 * This action is to adopt the volume by the command like: vol 50
 * the range of the volume is up -50 and below 50
 * @author CJ.Yang
 *
 */
class VolumeAct extends DefaultBaseAction implements Action {

	private boolean isSlient = false;
	public static final String cmd = "vol";
	private Integer volume;
	private Robot r;

	public VolumeAct(ActionFactory factory) {
		super(factory);
		try {
			r = new Robot();
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean checkCmd(String cmd) {
		String cmds[]=cmd.split(" ");
		if (cmds[0].equals(this.cmd)) {
			try{
			Integer vol=Integer.valueOf(cmds[1]);
			// check the value of volumne
			if(vol.intValue()>=-50&&vol.intValue()<=50){
				volume=vol;
				return true;
			}
			else{
				return false;
			}
			}catch(Exception e){
				// if the string is not digital..
				return false;
			}
		} else
			return false;
	}

	@Override
	public void setHandles(Object... hdls) {
		// TODO Auto-generated method stub

	}

	private void pressKey(Robot r, int keycode) {
		r.keyPress(keycode);
		r.keyRelease(keycode);
	}



	private void setVolInWin() throws IOException, InterruptedException {
		// check the exe file
		File file=new File("C:\\Windows\\system32\\sndvol32.exe");
		if(!file.exists())return;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec(file.getAbsolutePath());
		p.getInputStream();
		Thread.sleep(1000);
		r.setAutoDelay(100);
		pressKey(r, KeyEvent.VK_TAB);
		//pressKey(r, KeyEvent.VK_TAB);
		r.mouseWheel(volume);
		//pressKey(r, KeyEvent.VK_SPACE);
		pressKey(r, KeyEvent.VK_ALT);
		pressKey(r, KeyEvent.VK_P);
		pressKey(r, KeyEvent.VK_X);
		p.getOutputStream().close();
		p.waitFor();
		p.destroy();

	}

	private void setVolInUnix() {

	}

	@Override
	protected Object call0() {

		try {
			String osName = System.getProperty("os.name");
			if (osName.startsWith("Win")) {
				setVolInWin();
			} else if (osName.startsWith("Linux") || osName.startsWith("Mac")) {
				setVolInUnix();
			} else {// other os
			}

			isSlient = !isSlient;
			return "success";
		} catch (Exception e) {
			return e.getMessage();
		}

	}

}